package com.leetcode.solution.s2x;

import com.leetcode.solution.model.ListNode;

import java.util.List;

public class ReverseKGroup25 {
    public static void main(String[] args) {
        ListNode node = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
        ListNode head = new ReverseKGroup25().reverseKGroup(node, 2);
        while (head != null) {
            System.out.print(head.val + ", ");
            head = head.next;
        }

    }

    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode root = new ListNode(0, head);
        ListNode pre = root;
        ListNode tail = pre;
        ListNode next;
        while(head != null) {
            for(int i = 0; i < k; i++) {
                if (tail == null) {
                    break;
                }

                tail = tail.next;
            }

            if (tail == null) {
                break;
            }

            next = tail.next;
            ListNode[] listNodes = subReverse(head, tail);

            head = listNodes[0];
            tail = listNodes[1];

            pre.next = head;
            tail.next = next;

            pre = tail;
            head = tail.next;
        }


        return root.next;
    }

    private ListNode[] subReverse(ListNode head, ListNode tail) {
        ListNode pre = tail.next;
        ListNode curr = head;
        ListNode next;

        while(pre != tail) {
            next = curr.next;

            curr.next = pre;
            pre = curr;
            curr = next;
        }

        return new ListNode[] {tail, head};
    }
}
